<template>
  <div class="login">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <h3 class="title">Medical疫苗接种管理系统</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          placeholder="账号"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item prop="password" >
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="密码"
          show-password
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <!-- 验证码 -->
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="loginForm.code"
          placeholder="验证码"
          style="width: 63%"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code" style="width: 37%">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item>
      <!-- 记住密码 -->
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 100% 10px 0px;">记住密码</el-checkbox>
      <!-- 登录按钮 -->
      <el-form-item style="width: 100%">
        <el-button
          size="medium"
          type="primary"
          style="width: 100%"
          @click="doLogin()"
        >
          <span>登 录</span>
        </el-button>
      </el-form-item>
      <el-form-item style="width: 100%">
        <el-button
          size="medium"
          type="primary"
          style="width: 100%"
          @click="dialogVisible = true"
        >
          <span>注 册</span>
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 对话框 :rules="registerRules"  ref="form"-->
    <el-dialog :visible.sync="dialogVisible" title="注册账号" width="30%">
      <el-form :model="form"
               label-width="120px">
        <el-form-item label="名称">
          <el-input v-model="form.username" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="form.phone" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <!-- action表示为上传文件的url   -->
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8088/vaccinum/file/upload/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="form.code" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="form.sex" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="form.age" style="width: 80%"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save(form)">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2022 gec All Rights Reserved.</span>
    </div>
    <!--  -->


  </div>
</template>

<script>
import request from "@/utils/request";
import Cookies from "js-cookie";
import router from "@/router";
import {getCodeImg, login} from "../api/login";


export default {
  name: "Login",

  data() {
    return {
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        code: "",
        uuid: "",
      },
      form: {
        username: "",
        phone: "",
        password: "",
        image: "",
        code: "",
        email: "",
        sex: "",
        age: "",
      },
      imageUrl: "",
      loading: false,
      dialogVisible: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: true,
      loginRules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" }
        ]
      }
      //  registerRules: {
      //   name: [
      //     {required: true, trigger:"blur", message:"请输入您的昵称"},
      //     {min: 2, max: 12, message:"昵称长度在 2 到 12 个字符", trigger:"blur"}
      //   ],
      //   phone: [
      //     {required: true,trigger:"blur", message:"请输入您的手机号码"},
      //     {min: 11,max: 11,message: "手机号码长度为11个字符", trigger:"blur"},
      //     {validator: this.checkPhone, trigger:"blur"}
      //   ],
      //   password: [
      //    {required: true, trigger: "blur",message:"请输入密码"}
      //   ],
      //   code: [
      //   {required: true,trigger: "change", message:"请输入身份证号",message:"请输入邮箱"}
      //   ],
      //   email: [{required: true, trigger: "blur",message:"请输入邮箱"}],
      //   sex: [{required: true,trigger:"change",message:"请输入性别"}],
      //   age: [{required: true, trigger: "blur",message:"请输入年龄"}],
      // },

    };
  },
  created() {
    this.getCookie();
    this.getCode();
    this.getInfo();
  },
  methods: {
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : password,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    // 获取验证码
    getCode() {
      getCodeImg(this.loginForm.uuid).then(res => {
        if (res.code == "200") {
          this.codeUrl = "data:image/jpg;base64," + res.data.imgStr;
          this.loginForm.uuid = res.data.uuid;
          console.log(this.loginForm.uuid)
        }
      })
    },
    //登录
    doLogin() {
      // 规则校验
      this.$refs.loginForm.validate(valid => {
          if (valid){
            // 记住密码，将信息保存到cookie
            if (this.loginForm.rememberMe) {
              console.log(this.loginForm.rememberMe)
              Cookies.set("username", this.loginForm.username, { expires: 30 });
              //TODO 密码加密
              Cookies.set("password", this.loginForm.password, { expires: 30 });
              Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
            } else {
              Cookies.remove("username");
              Cookies.remove("password");
              Cookies.remove('rememberMe');
            }
            login(this.loginForm.username, this.loginForm.password, this.loginForm.code, this.loginForm.uuid)
              .then((res) => {
                if (res.code == 200) {
                  // 过期时间：3天
                  Cookies.set("token", res.data.token, {expires: 30})
                  this.$message({
                    message: "登录成功",
                    type: "success",
                  });
                  router.push("/");
                } else {
                  //登录失败
                  this.$message.error(res.message);
                }
              })
          }
      })
    },
    getInfo(){
      getInfo(this.loginForm.username).then((res) => {
        const user = res.data.user;
      })
    },
    //注册函数
    save(formName) {
      // this.$refs[formName]引用校验的表单对象  再通过表单对象来使用validate方法进行规则校验
      //发起post异步请求、提交数据
      request.post("/user/register", this.form).then((res) => {
        if (res.ok == true) {
          this.$message({
            type: "success",
            message: "添加成功",
          });
          //关闭对话框
          this.dialogVisible = false;
          //清空表单中的数据
          this.form = {};
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
      });

      // this.$refs[formName].validator((valid) => {
      //   if (valid) {
      //     //校验规则通过，则发起请求
      //     //发起post异步请求、提交数据
      //     request.post("/user/register", this.form).then((res) => {
      //       if (res.ok == true) {
      //         this.$message({
      //           type: "success",
      //           message: "添加成功",
      //         });
      //         //关闭对话框
      //         this.dialogVisible = false;
      //         //清空表单中的数据
      //         this.form = {};
      //       } else {
      //         this.$message({
      //           type: "error",
      //           message: res.message,
      //         });
      //       }
      //     });
      //   } else {
      //     console.log("error submit!!");
      //     return false;
      //   }
      // });
    },

    //成功后的处理函数
    handleAvatarSuccess(res, file) {
      console.log("file===" + file);
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.image = res

    },
    //上传之前的处理函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      console.log("isJPG===" + ((isJPG || isPNG) && isLt2M));
      return (isJPG || isPNG) && isLt2M;
    },
    handleEdit() {
      this.form = {};
      //3.显示对话框
      this.dialogVisible = true;
    },

  },
};
</script>

<style>
.login {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-image: url("../assets/welcome.jpg");
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  margin: 150px auto;
  background-color: rgba(90, 187, 211, 0.7);
  border-radius: 20px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
}

.el-input {
  height: 38px;
}

input {
  height: 38px;
}

.input-icon {
  height: 39px;
  width: 14px;
  margin-left: 2px;
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
